import React, { Component } from 'react';
import styled from 'styled-components/native';
import { MaterialIcons } from '@expo/vector-icons';
import Touchable from '@appandflow/touchable';
import { Platform, Keyboard, AsyncStorage } from 'react-native';
import { graphql, compose } from 'react-apollo';
import { connect } from 'react-redux';

import { TOKEN } from '../types';
import { colors, fakerAvatar } from '../utils/constants';
import SIGNUP_MUTATION from '../graphql/mutations/signup';
import Loading from '../components/Loading';
import { login } from '../actions/user';

const Root = styled(Touchable).attrs({
  feedback: 'none'
})`
  flex: 1;
  position: relative;
  align-items: center;
  justify-content: center;
`;

const BackButton = styled(Touchable).attrs({
  feedback: 'opacity'
}) `
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 5%;
  left: 5%;
  padding: 5px;
`;

const InputWrapper = styled.View`
  width: 100%;
  height: 50;
  border-color: ${colors.HR};
  border-bottom-width: 2;
  margin-vertical: 5;
  justify-content: flex-end;
`;

const Input = styled.TextInput.attrs({
  placeholderTextColor: colors.LITE_GRAY,
  selectionColor: Platform.OS === 'ios' ? colors.PRIMARY : undefined,
  autoCorrect: false
})`
  height: 30;
  color: ${props => props.theme.WHITE};
`;

const Wrapper = styled.View`
  width: 85%;
  min-height: 250;
`;

const ConfirmButton = styled(Touchable).attrs({
  feedback: 'opacity'
}) `
  width: 100%;
  height: 50;
  align-items: center;
  justify-content: center;
  background-color: ${props => props.theme.PRIMARY};
  border-radius: 10;
  shadow-opacity: 0.4;
  shadow-radius: 5;
  shadow-offset: 0 5px;
  shadow-color: #000;
  elevation: 5;
  margin-top: 75;
`;

const ConfirmButtomText = styled.Text`
  font-size: 20;
  font-weight: bold;
  color: ${props => props.theme.WHITE}
`;

class SignupForm extends Component {

  state = {
    fullname: '',
    email: '',
    password: '',
    username: '',
    loading: false
  }

  _onOutsidePressed = () => Keyboard.dismiss();

  _onChangeText = (type, value) => this.setState({ [type]: value });

  _checkIfCanSubmit = () => {
    const { fullname, email, password, username } = this.state;
    return fullname && email && password && username;
  }

  _onSignupPressed = async () => {
    this.setState({ loading: true });
    const { fullname, email, password, username } = this.state;
    const avatar = fakerAvatar;

    try {
      const { data } = await this.props.mutate({
        variables: {
          fullname,
          email,
          password,
          username,
          avatar
        }
      });

      await AsyncStorage.setItem(TOKEN, data.signup.token);
      this.setState({ loading: false });
      return this.props.login();
    } catch (error) {
      throw error;
    }
  }

  render() {
    if (this.state.loading) {
      return (
        <Loading />
      );
    }
    return (
      <Root onPress={this._onOutsidePressed}>
        <BackButton onPress={this.props.onBackPress}>
          <MaterialIcons color={colors.WHITE} size={30} name="arrow-back" />
        </BackButton>
        <Wrapper>
          <InputWrapper>
            <Input
              placeholder="Full Name"
              autoCapitalize="words"
              onChangeText={text => this._onChangeText("fullname", text)}
              value={this.state.fullname || ""}
            />
          </InputWrapper>
          <InputWrapper>
            <Input
              placeholder="Email"
              keyboardType="email-address"
              autoCapitalize="none"
              onChangeText={text => this._onChangeText("email", text)}
              value={this.state.email || ""}
            />
          </InputWrapper>
          <InputWrapper>
            <Input
              placeholder="Password"
              secureTextEntry
              onChangeText={text => this._onChangeText("password", text)}
              value={this.state.password || ""}
            />
          </InputWrapper>
          <InputWrapper>
            <Input
              placeholder="Username"
              autoCapitalize="none"
              onChangeText={text => this._onChangeText("username", text)}
              value={this.state.username || ""}
            />
          </InputWrapper>
          <ConfirmButton onPress={this._onSignupPressed} disabled={!this._checkIfCanSubmit()}>
            <ConfirmButtomText>Sign up</ConfirmButtomText>
          </ConfirmButton>
        </Wrapper>
      </Root>
    );
  }
}

export default compose(
  graphql(SIGNUP_MUTATION),
  connect(null, { login })
)(SignupForm);
